package cn.tedu.wallet.service.impl;

import cn.tedu.wallet.dao.repository.WalletRepository;
import cn.tedu.wallet.pojo.dto.UserTransactionRecordDTO;
import cn.tedu.wallet.pojo.param.RechargeParam;
import cn.tedu.wallet.pojo.param.RecordParam;
import cn.tedu.wallet.pojo.po.UserTransactionRecordPO;
import cn.tedu.wallet.pojo.po.UserWalletPO;
import cn.tedu.wallet.service.RecordService;
import cn.tedu.wallet.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;

@Service
@Slf4j
public class WalletServiceImpl implements WalletService {

    @Autowired
    private WalletRepository walletRepository;

    @Autowired
    RecordService recordService;

    @Override
    public void doRecharge(RechargeParam param) {
        log.info("用户{}进行充值操作，充值金额为：{}", param.getUserId(), param.getAmount());
        //新增充值订单记录
        log.debug("服务调用交易记录服务新增充值订单记录");
        RecordParam recordParam = new RecordParam();
        recordParam.setAccountUserId(param.getUserId());
        recordParam.setPayerUserId(param.getUserId());
        recordParam.setTransactionAmount(param.getAmount());
        recordParam.setTransactionTime(param.getTransactionTime());
        recordService.addRecord(recordParam);

        //获得当前余额
        log.debug("服务调用用户{}查询余额操作用于充值", param.getUserId());
        BigDecimal balance = walletRepository.doGetBalance(param.getUserId()).getBalance();
        BigDecimal newBalance = balance.add(param.getAmount());
        Date now = new Date();
        UserWalletPO po = new UserWalletPO();
        po.setUserId(param.getUserId());
        po.setBalance(newBalance);
        po.setUpdateTime(now);
        walletRepository.updateBalance(po);

    }

    @Override
    public String getBalance(Long userId) {
        log.info("服务调用用户{}查询余额操作", userId);
        BigDecimal balance = walletRepository.doGetBalance(userId).getBalance();
        //保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");
        String formattedBalance = df.format(balance);
        log.info("服务调用用户{}查询余额操作，余额为：{}", userId, formattedBalance);
        return formattedBalance;
    }
}
